﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using FineUIPro;
using Newtonsoft.Json.Linq ;
using FreeSql;


namespace FineUIPro
{
    public static partial class FineUIProExtensions
    {
        /// <summary>
        /// 动态创建Grid结构，在 Page_Init事件里执行（不是Page_Load事件里）
        /// </summary>
        /// <param name="Grid1">The grid1.</param>
        /// <param name="dt">The dt.</param>
        /// <param name="headerDic">dt列名称获取对应HeaderText</param>
        public static void CreatGridStructByDataTable(this FineUIPro.Grid Grid1, DataTable dt,Dictionary<string,string> headerDic=null)
        {
            FineUIPro.BoundField bf;

            if (headerDic == null || headerDic.Count == 0)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    bf = new FineUIPro.BoundField();
                    bf.DataField = dt.Columns[i].Caption;
                    bf.DataFormatString = "{0}";
                    bf.HeaderText = dt.Columns[i].Caption;
                    Grid1.Columns.Add(bf);
                }
            }
            else
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    bf = new FineUIPro.BoundField();
                    bf.DataField = dt.Columns[i].Caption;
                    bf.DataFormatString = "{0}";
                    bf.HeaderText = headerDic[dt.Columns[i].Caption];
                    Grid1.Columns.Add(bf);
                }
            }
        }

        /// <summary>
        /// 生成扩展列表格html,别忘记加css
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="showHeader">是否显示表格头</param>
        /// <param name="headerDic">dt列名称获取对应HeaderText(需要设置showHeader为true)</param>
        /// <param name="columnWidths">列宽度集合(数量要和dt列数一致 否则异常)</param>
        /// <returns></returns>
        public static string GetExpanderHtml(DataTable dt, bool showHeader = true, Dictionary<string, string> headerDic = null, int[] columnWidths=null)
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return string.Empty;
            }

            StringBuilder newLine = new StringBuilder();
            newLine.Append("<table class=\"mytable f-widget-header\">");
            //newLine.Append("<tr><td colspan=\String.Empty + dt.Columns.Count + "\" align=\"center\">" + dt.TableNameToClassName + "</td></tr>");
            if (showHeader)
            {
                newLine.Append("<tr>");
                if (columnWidths != null && columnWidths.Length > 0)//有列宽度
                {
                    if (headerDic != null && headerDic.Count > 0)//映射列名
                    {
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            newLine.AppendFormat("<th class=\"f-widget-header\" style=\"width:{1}px\">{0}</th>", headerDic[dt.Columns[i].Caption], columnWidths[i]);
                        }
                    }
                    else
                    {
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            newLine.AppendFormat("<th class=\"f-widget-header\" style=\"width:{1}px\">{0}</th>", dt.Columns[i].Caption, columnWidths[i]);
                        }
                    }
                }
                else
                {
                    if (headerDic != null && headerDic.Count > 0)//映射列名
                    {
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            newLine.AppendFormat("<th class=\"f-widget-header\">{0}</th>", headerDic[dt.Columns[i].Caption]);
                        }
                    }
                    else
                    {
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            newLine.AppendFormat("<th class=\"f-widget-header\">{0}</th>", dt.Columns[i].Caption);
                        }
                    }
                }
                newLine.Append("</tr>");
            }

            if (columnWidths != null && columnWidths.Length > 0)//有列宽度
            {
                //首行添加宽度
                newLine.Append("<tr>");
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    newLine.AppendFormat("<td class=\"f-widget-content\" style=\"width:{1}px\">{0}</td>", dt.Rows[0][i],columnWidths[i]);
                }
                newLine.Append("</tr>");
                //其他行
                for (int j = 1; j < dt.Rows.Count; j++)
                {
                    newLine.Append("<tr>");
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        newLine.AppendFormat("<td class=\"f-widget-content\">{0}</td>", dt.Rows[j][i]);
                    }
                    newLine.Append("</tr>");
                }
            }
            else
            {
                for (int j = 0; j < dt.Rows.Count; j++)
                {
                    newLine.Append("<tr>");
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        newLine.AppendFormat("<td class=\"f-widget-content\">{0}</td>", dt.Rows[j][i]);
                    }
                    newLine.Append("</tr>");
                }
            }
            newLine.Append("</table>");
            return newLine.ToString();

            /* //所需的css，参考：https://pro.fineui.com/#/grid/grid_rowexpander_htmlgrid.aspx
    <style>
        .mytable {border-width: 1px;border-style: solid;border-collapse: separate;border-spacing: 0;border-bottom-width: 0;border-right-width: 0;}
        .mytable th,.mytable td {padding: 5px;text-align: left;border-bottom-width: 1px;border-bottom-style: solid;border-right-width: 1px;border-right-style: solid;}
    </style>
             */

            /* //调用示例
              lit.Text = FineUIProExtensions.GetExpanderHtml(GetDataTable(),
                headerDic:new Dictionary<string, string>(){{"id","主键"},{ "name", "内容"},{ "age", "年龄"}}, 
                columnWidths:new int[]{100,300,120});
             */

            /* //如果数据和样式比较复杂。只能手写，例如下面的，选项字段，文本右对齐
    public static string GetGoodsExpanderHtml(DataRow[]  rows)
    {
        if (rows == null || rows.Length == 0)
        {
            return string.Empty;
        }

        StringBuilder newLine = new StringBuilder();
        newLine.Append("<table class=\"mytable f-widget-header\">");
        //newLine.Append("<tr><td colspan=\String.Empty + drs[0].Table.Columns.Count + "\" align=\"center\">" + dt.TableNameToClassName + "</td></tr>");
        newLine.Append("<tr>");
        newLine.Append("<th class=\"f-widget-header\" style=\"width:120px\">物品类型</th>");
        newLine.Append("<th class=\"f-widget-header\" style=\"width:200px\">物品名称</th>");
        newLine.Append("<th class=\"f-widget-header\" style=\"width:200px\">物品编码</th>");
        newLine.Append("<th class=\"f-widget-header\" style=\"width:120px\">规格</th>");
        newLine.Append("<th class=\"f-widget-header\" style=\"width:120px\">颜色</th>");
        newLine.Append("<th class=\"f-widget-header\" style=\"width:80px;text-align:right\">数量</th>");
        newLine.Append("</tr>");

        for (int j = 0; j < rows.Length; j++)
        {
            newLine.Append("<tr>");
            newLine.AppendFormat("<td class=\"f-widget-content\">{0}</td>", rows[j]["type"]);
            newLine.AppendFormat("<td class=\"f-widget-content\">{0}</td>", rows[j]["title"]);
            newLine.AppendFormat("<td class=\"f-widget-content\">{0}</td>", rows[j]["code"]);
            newLine.AppendFormat("<td class=\"f-widget-content\">{0}</td>", rows[j]["size"]);
            newLine.AppendFormat("<td class=\"f-widget-content\">{0}</td>", rows[j]["color"]);
            newLine.AppendFormat("<td class=\"f-widget-content\" style=\"text-align:right\">{0}</td>", rows[j]["num"]);
            newLine.Append("</tr>");
        }
        newLine.Append("</table>");
        return newLine.ToString();
    }
             */
        }

        /// <summary>
        /// 获取选中行的主id
        /// </summary>
        /// <param name="grid">FineUIPro.Grid</param>
        /// <param name="keyNumIndex">第几个主键（从0开始）</param>
        /// <returns></returns>
        public static string GetDataKeysBySelectedRow(this FineUIPro.Grid grid, int keyNumIndex = 0)
        {
            //需要正确设置grid DataKeyNames主键列名
            int[] selections = grid.SelectedRowIndexArray;//获取选中行
            if (selections.Length == 0)
            {
                return string.Empty;
            }

            StringBuilder sb = new StringBuilder();
            foreach (int rowIndex in selections)
            {
                sb.Append("," + grid.DataKeys[rowIndex][keyNumIndex].ToString());
            }

            return sb.ToString().Substring(1);
        }

        /// <summary>
        /// 获取选中行的主id
        /// </summary>
        /// <param name="grid">FineUIPro.Grid</param>
        /// <param name="keyNumIndex">第几个主键（从0开始）</param>
        /// <returns></returns>
        public static List<int> GetDataKeysListBySelectedRow(this FineUIPro.Grid grid, int keyNumIndex = 0)
        {
            //需要正确设置grid DataKeyNames主键列名
            int[] selections = grid.SelectedRowIndexArray;//获取选中行
            if (selections.Length == 0)
            {
                return null;
            }

            List<int> list = new List<int>();
            foreach (int rowIndex in selections)
            {
                list.Add(int.Parse(grid.DataKeys[rowIndex][keyNumIndex].ToString()));//获取每行第keyNumIndex个主键
            }
            return list;
        }
        

        public static List<TGridViewModel> BindFineuiByFreeSql<TGridViewModel>(this FineUIPro.Grid grid,ISelect<TGridViewModel> iSelect) where TGridViewModel : class
        {
            long recordCount = 0;

            List<TGridViewModel> data = iSelect.Count(out recordCount).Page(grid.PageIndex + 1, grid.PageSize).ToList();

            grid.RecordCount = (int)recordCount;
            grid.DataSource = data;
            grid.DataBind();
            return data;
        }
        


        // /// <summary>
        // /// 查询数据库记录条数
        // /// </summary>
        // /// <param name="sql"></param>
        // /// <returns></returns>
        // private static int GetdataTableCount(string sql)
        // {
        //     var db =  FreeSqlHelper.GetInstance();
        //     object cnt = db.Ado.GetScalar(sql);
        //     return Convert.ToInt32(cnt);
        // }


        #region 脚本相关

        /// <summary>
        /// 获取可编辑grid是否删除选中行的脚本
        /// </summary>
        /// <param name="grid"></param>
        /// <param name="title">标题</param>
        /// <param name="message">消息提示</param>
        /// <param name="cancelScript">关闭时候运行的js</param>
        /// <returns></returns>
        public static string GetDeleteSelectedScript(this FineUIPro.Grid grid,string title="",string message= "删除选中行？",string cancelScript="")
        {
            return Confirm.GetShowReference(message, title, MessageBoxIcon.Question, grid.GetDeleteSelectedRowsReference(), cancelScript);
        }
        /// <summary>
        /// 获取可编辑grid是否删除选中行的html
        /// </summary>
        /// <param name="grid"></param>
        /// <param name="title">标题</param>
        /// <param name="message">消息提示</param>
        /// <param name="cancelScript">关闭时候运行的js</param>
        /// <returns></returns>
        public static string GetDeleteSelectedHtml(this FineUIPro.Grid grid,string title="",string message= "删除选中行？",string cancelScript="")
        {
            return String.Format("<a href=\"javascript:;\" onclick=\"{0}\"><img src=\"{1}\"/></a>", grid.GetDeleteSelectedScript(title, message ,  cancelScript ), IconHelper.GetResolvedIconUrl(Icon.Delete));
        }
        #endregion
    }
}

